<?php
require_once('model/Customer.php');

class Customer extends DataObjects_Customer 
{
	
	public function checkPermission()
	{
		 
		$contr = FRM_Request::getController();
		$contr = substr($contr, strpos($contr, '_') + 1);
	
		$current_user = unserialize(FRM_Session::get('user_serialize'));
	
		if ($current_user && $current_user->id)
		{
			return true;
		}
		else
		{
			FRM::redirect(APPLICATION_URL . '/user/login/');
		}
	}
	/**
	 * create user
	 *
	 */
	function create()
	{
		$this->password = sha1($this->password);
		$this->lastvisit = date('Y-m-d H:i:s');
		$id = $this->insert();
	
		if (!$this->id)
		{
			$this->id = $this->id;
			$this->update();
				
		}
	}
	
	/**
	 * validate user input
	 *
	 * @return bool true if user input is valid, otherwise return false
	 */
	function validateInput()
	{
		if ($this->id)
		{
			return $this->validateEmail();
		}
		else
		{
			return $this->validateEmail() && $this->validatePassword() && $this->validateConfirmPassword();
		}
	}
	
	/**
	 *	validate email
	 *
	 * @return bool true if email is valid, otherwise return false
	 */
	function validateEmail()
	{
		if ($this->email == '')
		{
			ErrorHandler::add('_ERR_EMAIL_CANNOT_BE_EMPTY');
			return false;
		}
		if (!Utils::checkEmailValid($this->email))
		{
			ErrorHandler::add('_ERR_INVALID_EMAIL');
			return false;
		}
	
		if (Customer::checkUserExist($this->username))
		{
			ErrorHandler::add('_ERR_USERNAME_EXIST');
			return false;
		}
		
		if (Customer::checkEmailExist($this->email))
		{
			ErrorHandler::add('_ERR_EMAIL_EXIST');
			return false;
		}
		
		return true;
	}
	
	/**
	 * validate password
	 *
	 * @return bool true if password is valid, otherwise return false
	 */
	function validatePassword()
	{
		if (strlen($this->password) <= 0 )
		{
			ErrorHandler::add('_ERR_PASSWORD_CANNOT_BE_EMPTY');
			return false;
		}
	
		if (strlen($this->password) < 6 )
		{
			ErrorHandler::add('_ERR_MIN_LENGTH_PASSWORD_SERVER');
			return false;
		}
	
		if (strlen($this->password) > Parameter::MAX_LENGTH_PASSWORD)
		{
			ErrorHandler::add('_ERR_MAX_LENGTH_PASSWORD_SERVER');
			return false;
		}
		return true;
	}
	
	/**
	 * validate confirm password
	 *
	 * @return bool true if confirm password is valid, otherwise return false
	 */
	function validateConfirmPassword()
	{
		if ($this->password != $this->confirm_password)
		{
			ErrorHandler::add('_ERR_INVALID_CONFIRM_PASSWORD');
			return false;
		}
		return true;
	}
	
	/**
	 * Check the user is exist
	 *
	 * @param string $email
	 * @return boolean if the user is exist return true otherwise return false
	 */
	public static function checkUserExist($username)
	{
		$customer = new Customer();
		$customer->username = $username;
		$customer->find();
		
		return $customer->N > 0;
	}
	
	/**
	 * Check the email is exist
	 *
	 * @param string $email
	 * @return boolean if the email is exist return true otherwise return false
	 */
	public static function checkEmailExist($email)
	{
		$customer = new Customer();
		$customer->email = $email;
		$customer->find();
		
		return $customer->N > 0;
	}
	
	/*
	 * Perform login
	* @param string $username
	* @param string $password
	*
	* return array $error
	*/
	public static function performLogin($username, $password)
	{
		$errors = NULL;
	
		// free all SESSION variables
		FRM_Session::remove();
			
		//Cfer::setBackLink("login");
	
		$customer = new Customer();
		$customer->connectUser($username, $password);
	
		if (sizeof($errors) == 0)
		{
			if ($customer->id <> NULL)
			{
				FRM_Session::set('user_serialize', serialize($customer) );
			}
			else
			{
				if ($customer->id <> NULL)
					$errors[] = '_LB_NOT_GRANTED';
				else
					$errors[] = '_LB_INVALID_LOGIN_OR_PASSWORD';
			}
		}
	
		return $errors;
	}
	
	// check login and use SHA1 to encode password
	function connectUser($login, $password, $encode_password = true)
	{
		$this->whereAdd("username = '" . $this->escape($login) . "'");
		$this->whereAdd("password = '" . (($encode_password) ? sha1($this->escape($password)) : $this->escape($password)) . "'");
	
		$this->selectAdd();
		$this->selectAdd('customer.*');
	
		$this->find();
		
		if ($this->N)
		{
			$this->fetch();
		}
	}
	
	/**
	 * Get all customer
	 *
	 * @return customer object
	 */
	public function getList($filter = array()){
		
		$customer = new Customer();
		
		if(isset($filter['date_create']) && $filter['date_create']){
			$customer->whereAdd("DATE_FORMAT(date_create, '%Y-%m-%d') = '".$filter['date_create']."'");
		}
		
		$customer->orderBy('id');
		$p = new FRM_Pager('page',Parameter::$params["PAGING_DEFAULT_ITEM_PER_PAGE"], new FRM_Pager_RangeIterator(1, Parameter::$params['PAGING_DEFAULT_PAGE_DELTA'], 1));
		$customer->setPager($p);
		$customer->find();
		//echo $customer->getSelectSQL(); die;
		return $customer;
	}
	
	public function sendMailForgotPassword($newpass){
	
		$email_support = Parameter::$params['EMAIL_SUPPORT'];
	
		$from = Parameter::$params['EMAIL_SERVER'];
		$to = $this->email ;
	
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
	
		// Additional headers
		$headers .= 'To: '.$to . "\r\n";
		$headers .= 'From: '.$from. "\r\n";
		$subject = "You have forgotten password on website";
	
		$smarty = FRM::load('smarty');
		$smarty->assign('customer', $this);
		$smarty->assign('newpass', $newpass);
	
		$message= $smarty->fetch('public/email-forgotpassword.html');
		return MailSMTP::send($to, $subject, $message);
	}
	public static function changeForgotPassword($email){
		$customer = new Customer();
		$customer->get('email', $email);
	
		if (!$customer->N)
			return false;
	
		$chars = 'abcdefghijklmnopqxyz0123456789';
		$newpass = '';
		for ($i = 0; $i < 8; $i ++){
			$newpass .= $chars[rand(0, strlen($chars) - 1)];
		}
	
		$customer->password = sha1($newpass);
		$customer->update();
	
		$customer->sendMailForgotPassword($newpass);
	
		return true;
	}
	
	public function sendMailSignUp($customer){
	
		$email_support = Parameter::$params['EMAIL_SUPPORT'];
	
		$from = Parameter::$params['EMAIL_SERVER'];
		$to = $customer->email ;
	
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
	
		// Additional headers
		$headers .= 'To: '.$to . "\r\n";
		$headers .= 'From: '.$from. "\r\n";
		$subject = Parameter::$params['EMAIL_SUBJECT_SIGNUP'];
	
		$smarty = FRM::load('smarty');
		$smarty->assign('customer', $customer);
        $message = $smarty->fetch('public/email-signup.html');
        
		return MailSMTP::send($to, $subject, $message);
	}

}
?>